/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BankClientPrototype;

import java.sql.*;
import java.util.Vector;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author sjt5097
 */
public class ClientHandler extends Thread {

    private static int accountStore;
    private static String FirstName = "";
    private static String accountType;
    private static double amount = 0.0;

    public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();

        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }

        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                vector.add(rs.getObject(columnIndex));
            }
            data.add(vector);
        }
        return new DefaultTableModel(data, columnNames);
    }

    public static void main(String[] args) throws InterruptedException {
        ClientLogin cl = new ClientLogin();
        cl.setVisible(true);
    }

    protected int fromLogin(ClientLogin cl, String username, char[] password, ClientHomepage ch) {
        EncryptUtils encrypt = new EncryptUtils();
        String temp = new String(password);
        String xor = encrypt.xorMessage(temp, "VedishShahSeanTeevanRyanDwyer");
        String pass = encrypt.base64encode(xor);
        System.out.println("Encryption is: " + pass);
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:Client");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM OnlineInfo WHERE UserName = '" + username + "' AND Password = '" + pass + "'");
            while (rs.next()) {
                accountStore = rs.getInt("AccountNumber");
                ResultSet rs1 = stmt.executeQuery("SELECT FirstName FROM UserInfo WHERE SavingsAccount = " + accountStore + " OR CheckingAccount = " + accountStore + "");
                while (rs1.next()) {
                    String fName = rs1.getString("FirstName");
                    setFName(fName);
                    ResultSet rs2 = stmt.executeQuery("SELECT AccountType, Amount FROM Accounts WHERE AccountNumber = " + accountStore + "");
                    while(rs2.next())
                    {
                        double amount = rs2.getDouble("Amount");
                        setAmount(amount);
                        String aType = rs2.getString("AccountType");
                        setAType(aType);
                        con.close();
                        ch = new ClientHomepage();
                        ch.setVisible(true);
                        cl.setVisible(false);
                        cl.dispose();
                    }
                }
            }
//            JDialog dlg = new JDialog(cl, "The username or password does not match our records.");
//            dlg.setVisible(true);
        } catch (Exception e) {
        }
        return accountStore;
    }

    protected void TransDisplay() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:odbc:Client");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM Transactions WHERE AccountFrom = " + accountStore + " OR AccountTo = " + accountStore + "");
            JTable table = new JTable(ClientHandler.buildTableModel(rs));
            JOptionPane.showMessageDialog(null, new JScrollPane(table));
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void toLoginFromHome(ClientHomepage ch) {
        ClientLogin cl = new ClientLogin();
        cl.setVisible(true);
        ch.setVisible(false);
        ch.dispose();
    }

    protected void fromTransfer(ClientTransfer ct) {
        ClientHomepage ch = new ClientHomepage();
        ch.setVisible(true);
        ct.setVisible(false);
        ct.dispose();
    }

    protected void toTransfer(ClientHomepage cHome) {
        ClientTransfer ct = new ClientTransfer();
        ct.setVisible(true);
        cHome.setVisible(false);
    }

    protected String getFName() {
        return FirstName;
    }

    protected void setFName(String FName) {
        System.out.println(FName);
        FirstName = FName;
    }
    
    protected double getAmount() {
        return amount;
    }

    protected void setAmount(double amt) {
        amount = amt;
    }
    
    protected String getAType() {
        return accountType;
    }

    protected void setAType(String AType) {
        if(AType.equals("S"))
            accountType = "Savings";
        else
            accountType = "Checking";
    }

    protected void fromRegister(ClientRegister cr) {
        ClientLogin frame = new ClientLogin();
        frame.setVisible(true);
        cr.setVisible(false);
    }

    protected boolean registering(String userName, char[] password, int savings, int checking) {
        EncryptUtils encrypt = new EncryptUtils();
        String temp = new String(password);
        String xor = encrypt.xorMessage(temp, "VedishShahSeanTeevanRyanDwyer");
        String pass = encrypt.base64encode(xor);
        System.out.println("Encryption is: " + pass);
        if (savings != 0) {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM Accounts WHERE AccountNumber = " + savings + "");
                while (rs.next()) {
                    stmt.executeUpdate("INSERT INTO OnlineInfo (UserName, Password, AccountNumber) VALUES ('" + userName + "', '" + pass + "', " + savings + ")");                    System.out.println("Inserted");
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else if (checking != 0) {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM Accounts WHERE AccountNumber = " + checking + "");
                while (rs.next()) {
                    stmt.executeUpdate("INSERT INTO OnlineInfo (UserName, Password, AccountNumber) VALUES ('" + userName + "', '" + pass + "', " + checking + ")");
                    con.close();
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return false;
        }
        return false;
    }


    /*
     * doTransfer() is a method that connects to the database
     * It takes the originating account (accountFrom) and the
     * destination account (accountTo), as well as the amount
     * to be transfered.  This method extracts the data to be
     * edited, modifies them, and injects them back into the
     * database in the proper places.
     */
    protected void doTransfer(int accountFrom, int accountTo, double amount) {
        boolean success;
        if (accountFrom == accountStore) {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("jdbc:odbc:Client");
                Statement stmt = con.createStatement();
                //Amount is taken from originating account first
                ResultSet rs1 = stmt.executeQuery("SELECT Amount FROM Accounts WHERE AccountNumber = " + accountFrom + "");
                while (rs1.next()) {
                    double origAmt = rs1.getFloat("Amount");
                    double newAmt = origAmt - amount;
                    stmt.executeUpdate("UPDATE Accounts SET Amount = " + newAmt + " WHERE AccountNumber = " + accountFrom + ";");
                    ResultSet rs2 = stmt.executeQuery("SELECT Amount FROM Accounts WHERE AccountNumber = " + accountTo + "");
                    while (rs2.next()) {
                        double origAmt2 = rs2.getFloat("Amount");
                        double newAmt2 = origAmt2 + amount;
                        stmt.executeUpdate("UPDATE Accounts SET Amount = " + newAmt2 + " WHERE AccountNumber = " + accountTo + ";");
                        stmt.executeUpdate("INSERT INTO Transactions (AccountFrom, AccountTo, Amount, LoggedTime) VALUES (" + accountFrom + ", " + accountTo + ", " + amount + ", now());");
                        con.close();
                    }
                }
            } catch (Exception e) {
            }
        } else {
            JOptionPane.showMessageDialog(null, "Our records indicate that you do"
                    + " not own one of the accounts specified. \n Transfer Failed");
        }
        JOptionPane.showMessageDialog(null, "Transfered Successfully");
    }
}
